package backend;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.ws.Action;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;



public class Connection {

	static String serviceUrl;
	
	private Connection(){
		
	}
		
	public static void setServiceUrl(String url){
		serviceUrl=url;
	}
	
    @Action
    public static Document connect(String function,String method,String [] args) throws Exception {

            // Thanks: http://xml.nig.ac.jp/tutorial/rest/index.html
    		
        URL url;
        URLConnection urlc=null;
        
        
        
        String pargs=parseArgs(args);
        

        if (method.equals("GET")){
        	url = new URL(serviceUrl+"?method="+function+"&"+pargs);
            urlc = url.openConnection();
            urlc.setDoOutput(false);
            urlc.setAllowUserInteraction(false);
        }
        else if (method.equals("POST")){
        	url = new URL(serviceUrl+"?method="+function);
        
        	urlc = url.openConnection();
            urlc.setDoOutput(true);
            urlc.setAllowUserInteraction(false);
            String encodedPost = URLEncoder.encode(pargs,"UTF-8");
                        
            PrintStream ps = new PrintStream(urlc.getOutputStream());
            ps.print("account=" + encodedPost);
            ps.close();
        	
        }
   
        //retrieve result
        BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
                
        String str;
        StringBuffer sb = new StringBuffer();
        

        
        while ((str = br.readLine()) != null) {
            sb.append(str);
            sb.append("\n");
        }
        br.close();
        String response = sb.toString();
 
        if (response == null) {
        	throw new Exception("Not Response From Server");
        }
        
        
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(response));
        Document dom = db.parse(is);
        
        checkFail(dom);
        
        return dom;
        
    }
    
    
    
    
    
    
    private static void checkFail(Document dom) throws Exception{
    	
    	Node status = dom.getElementsByTagName("response").item(0).getAttributes().getNamedItem("status");
		
		if (status.getNodeValue().equals("fail")){
			
			NamedNodeMap error=dom.getElementsByTagName("error").item(0).getAttributes();
			
			String code=error.getNamedItem("code").getNodeValue();
			String descr=error.getNamedItem("message").getNodeValue();;
			
			//ACA HABRIA Q TRADUCIR E ENVIAR EL MENSAJE CORRECTO
			throw new Exception ("codigo: "+code+" - descr: "+descr);
		}
    }
    	
    	
    	
  
    private static String parseArgs(String[] args) {
    		
    	String allArgs="";
    	
    	if (args!=null){
	    	for(String a: args){
	    		allArgs=!allArgs.equals("")?allArgs+"&"+a:a;
	    	}
    	}

    	return allArgs;
	}
	
	
}
